package cn.csust.net2.manager.server.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.SQLQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import cn.csust.net2.manager.shared.exception.BeyondAuthorityException;
import cn.csust.net2.manager.shared.po.Research;
import cn.csust.net2.manager.shared.po.ResearchAnswer;
import cn.csust.net2.manager.shared.po.ResearchResult;
import cn.csust.net2.manager.shared.po.ResearchTitle;
import cn.csust.net2.manager.shared.service.ResearchManagerService;
import cn.csust.net2.manager.shared.util.ServiceConstant;
@Service(value = ServiceConstant.SERVICE_NAME_RESEARCH_MANAGER)
public class ResearchManagerServiceImpl extends ResearchCommanServiceImpl implements ResearchManagerService{

	@Transactional
	@Override
	public void saveResearchStudentsByPaging(PagingLoadConfig config) throws BeyondAuthorityException{
		Long researchID  = config.get(RESEARCHID);
		List<Long>  numberList  = config.get(STUDENT_NUMBERL_LIST);
		
		//首先删除reserchID 为此id 的所有项
		String delSql = "DELETE FROM `manager`.`student_research` WHERE researchID = " + researchID;
		getResearchDAO().getCurrentSession().createSQLQuery(delSql).executeUpdate();
		if(researchID!=null&&numberList!=null){
			for(int i= 0;i<numberList.size();i++){
				String sql = "INSERT INTO `manager`.`student_research`(`studentNumber`,`researchID`) VALUES ( "+numberList.get(i)+","+researchID+")";
				SQLQuery q = getResearchDAO().getCurrentSession().createSQLQuery(sql);
				q.executeUpdate(); 
			}
		}
		
		
	}

	@Transactional
	@Override
	public List<Long> getResearchStudentNumberList(Long researchID)throws BeyondAuthorityException {
		List <Long> list  = new ArrayList<Long>();
		if(researchID!=null){
			String sql = "SELECT studentNumber FROM `manager`.`student_research` WHERE researchID = " + researchID;
			List<BigInteger> nums =  getResearchDAO().findListBySQL(sql);
			for(BigInteger l : nums){
				list.add(l.longValue());
			}
			return list;
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 *  此方法备用与统计调研
	 */
	@Transactional
	@Override
	public Map<Long , List<ResearchResult>>  statisticsResearchResult(PagingLoadConfig config)throws BeyondAuthorityException {
		Long researchID = config.get(RESEARCHID);
		Long number = config.get(STUDENT_NUMBER);
		Map<Long , List<ResearchResult>>  map  =  new HashMap<Long, List<ResearchResult>>();
		if(researchID!=null&&number!=null){
			String sql = "SELECT titleID FROM researchtitle WHERE researchID  = " + researchID;
			List<Long> tIDs = getResearchResultDAO().findListBySQL(sql);
			for(long id : tIDs){
				String hql = " from ResearchResult as rs where rs.title.titleID = " + id + " and rs.userId = "+ number;
				map.put(id, getResearchResultDAO().findListByHQL(hql));
			}
			return map;
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * @see cn.csust.net2.manager.shared.service.ResearchManagerService#statisticsResearchResultPolls(com.extjs.gxt.ui.client.data.PagingLoadConfig)
	 * 返回answer的id及对应的票数
	 */
	@Transactional
	@Override
	public Map<Long, Long> statisticsResearchResultPolls(
			PagingLoadConfig config)throws BeyondAuthorityException {
		Long researchID = config.get(RESEARCHID);
//		Long number = config.get(STUDENT_NUMBER);
		List<Long> numberList= config.get(STUDENT_NUMBERLIST);
		Map<Long, Long> map = new HashMap<Long, Long>();
		if(researchID!=null){
			String rsql = "SELECT titleID FROM researchtitle WHERE researchID  = " + researchID;
			//选出所有题目的id
			List<BigInteger> tIDs = getResearchResultDAO().findListBySQL(rsql);
			for(BigInteger tid : tIDs){
				String tsql = " SELECT answerID FROM researchanswer WHERE titleID = " + tid ;
				//选出所有答案的id
				List <BigInteger> aIDs = getResearchAnswerDAO().findListBySQL(tsql);
				for(BigInteger aid : aIDs){
					//从research_research中徐选出 所有答案的投票的数量统计
//					String hql  = "from ResearchAnswer as ra where ra.title.titleID = " + " and ra.answer.answerId = " + aid;
					String sql = " SELECT * FROM `manager`.`researchResult` WHERE titleID = "+tid +" AND answerID = " + aid;
					if(numberList != null){
						sql += " AND ( ";
						for(long l : numberList){						
							 sql += "userID = " + l + " OR ";
						}
						sql = sql.substring(0, sql.lastIndexOf("OR"));
						sql +=")";
					}
					System.out.println(sql+"===========================================");
					long count = getResearchResultDAO().countsBySQL(sql);
					map.put(new Long(aid.longValue()), count);
				}
			}
			System.out.println("后台+++++++++++++++++++++++++++："+ map);
			return map;
		}
		return null;
	}
	
	@Transactional
	@Override
	public void saveResearchByPaging(PagingLoadConfig config)throws BeyondAuthorityException {
		Research research = config.get(RESEARCH);
		Set<ResearchTitle> titleSet = config.get(RESEARCH_TITLE_SET);
		Set<ResearchAnswer> answerSet = config.get(RESEARCH_ANSWER_SET);
		if(research!=null&&titleSet!=null&&answerSet!=null){
			getResearchDAO().save(research);
			for(ResearchTitle rt : titleSet){
				getResearchTitleDAO().save(rt);
			}
			for(ResearchAnswer ra : answerSet){
				getResearchAnswerDAO().save(ra);
			}
		}
		
		
	}
}
